<script lang="ts" setup>
import type { OrderItem } from '@/types/api/order'
import type { Ref } from 'vue'
import { orderApi } from '@/request/api'
import { useDict } from '@/stores/index'
import { DictCode } from '@/types/api/public'
import {
  useConsole,
  useDayjsFormat,
  useHideLoading,
  useLoading,
  useNav,
  useparticularly,
  useRouteGuard,
  useToast,
} from '@/utils'
import {
  handleChaKanZhangDan,
  handleFengKongBuLu,
  handleFuWuBaoZhang,
  handleLianXiShangJia,
  handleMaiDuan,
  handleQianChengNuoShu,
  handleQianShouDan,
  handleQianShuDaiKou,
  handleQianShuHeTong_JunZiQian,
  handleQueRenShouHuo,
  handleQuXiaoDingDan,
  handleShenQingGuiHuan,
  handleShenQingTuiKuan,
  handleShouHuoBuLu,
  handleWeiYueJin,
} from '@/utils/order-operation'
import { useOrderStatusCheck } from '@/utils/order-status-check'
import { onLoad, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty, isNil } from 'lodash-es'
import { computed, ref } from 'vue'
import { object as zobject, string as zstring } from 'zod'

interface Schedule {
  date: string
  price: string
  _status: number
}
const { getRent } = useparticularly()
const flagRent = getRent()
const oid = ref() as Ref<number>
const detail = ref() as Ref<OrderItem>
const expand = ref(false)
const dict = useDict()
/** 物流 */
const logistics = computed(() => {
  const data = detail.value?.productOrderShipment?.cont?.data
  if (isEmpty(data)) {
    return {
      show: false,
      data: [],
    }
  }
  return {
    show: true,
    data,
  }
})
const scheduleList = computed<Schedule[]>(() => {
  if (isNil(detail.value)) {
    return []
  }

  // 未产生订单时使用下单时前端传递的参数
  if (isEmpty(detail.value.productOrderRecordVoList)) {
    return detail.value.params.orderPriceList.map((x) => {
      return {
        date: x.date,
        price: x.price,
        // _status: isEmpty(detail.value.productOrderRecordVoList?.[i]?.paymentRecordList) ? 0 : 1,
        _status: 0,
      }
    })
  }
  // 已产生订单时使用后端计算的
  else {
    return detail.value.productOrderRecordVoList.map((x) => {
      return {
        date: useDayjsFormat(x.expiretime, 'DD'),
        price: (x.price / 100).toFixed(2),
        _status: x.payment,
      }
    })
  }
})
const packageName = computed(() => {
  return detail.value.params.detail
    .split(' ')
    .map((part, index) =>
      index === 0 ? dict.operateDict(part)?.itemText ?? part : part,
    )
    .join(' ')
})
onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }
  oid.value = zparse.data.oid
  await dict.init({ dictCode: DictCode.rentType })
  await getDetail()

  uni.$on('refreshOrderDetail', async () => {
    useLoading(true)
    await getDetail()
    useHideLoading()
  })
})

onPullDownRefresh(async () => {
  await getDetail()
  uni.stopPullDownRefresh()
})

async function getDetail() {
  const [err, res] = await to(orderApi.detail(oid.value))
  if (err) {
    return
  }
  useConsole?.log('res', res)
  detail.value = res
}

function handleCopyOrderCode() {
  uni.setClipboardData({
    data: detail.value.ordercode,
    success: () => useToast('已复制'),
  })
}

function handleNavProductDetail() {
  useNav('/product/detail', { id: detail.value.params.id })
}
</script>

<template>
  <view v-if="!isNil(detail)" class="min-h-100vh flex flex-col">
    <view class="flex-1">
      <view class="px-30px py-20px">
        <!--  -->
        <view
          class="min-h-120px flex items-center rd-16px bg-white py-20px pl-30px pr-20px"
        >
          <view class="bg-theme-primary h-48px w-48px flex shrink-0 rd-full">
            <view
              class="i-fluent:location-28-filled m-a text-30px text-white"
            ></view>
          </view>
          <view class="ml-20px flex flex-col text-24px">
            <view class="text-#3 routine-lh">{{ detail.province }}{{ detail.city }}{{ detail.district
            }}{{ detail.address }}</view>
            <view class="mt-10px text-#6">{{ detail.tit }} {{ detail.phone }}</view>
          </view>
        </view>

        <!--  -->
        <view class="mt-10px rd-16px bg-white px-20px pt-20px">
          <view class="flex items-center pl-10px text-24px">
            <view class="text-#3">订单编号</view>
            <view class="ml-10px text-#6">{{ detail.ordercode }}</view>
            <view
              class="ml-a px-15px lh-40px btn-secondary-theme"
              @click="handleCopyOrderCode"
            >复制</view>
          </view>
          <view
            class="mt-24px flex items-start"
            @click="handleNavProductDetail"
          >
            <image
              class="h-200px w-200px shrink-0 rd-20px bg-gray-50"
              :src="detail.params.image"
              mode="aspectFit"
            >
            </image>
            <view class="ml-16px flex flex-col py-10px">
              <view class="text-30px text-#3 lh-35px">{{
                detail.params.title
              }}</view>
              <view
                class="grid grid-cols-[auto_1fr] mt-15px gap-x-10px gap-y-10px text-24px"
              >
                <view class="text-#6a routine-lh">已选:</view>
                <view class="text-#3 routine-lh">{{ packageName }}</view>
                <view class="text-#6a">总租金:</view>
                <view class="text-theme-red">¥&thinsp;{{
                  (detail.params.model.price / 100).toFixed(2)
                }}</view>
                <view class="text-#6a">实付款:</view>
                <view class="text-theme-red">¥&thinsp;{{ (detail.params.deposit / 100).toFixed(2) }}</view>
                <view class="text-#6a">数量:</view>
                <view class="text-theme-red">{{ detail.num }}</view>
              </view>
            </view>
          </view>
          <template v-if="expand">
            <view class="mt-30px b-t-1px b-t-#e0 b-t-solid px-15px pb-30px">
              <view class="h-70px flex items-center">
                <view class="text-28px text-#3">订单信息</view>
              </view>
              <view class="grid grid-cols-[auto_1fr] gap-y-20px text-24px">
                <!-- <view class="text-#6">物流公司</view>
                <view class="text-right text-#3">寄出包邮/顺丰包邮</view> -->
                <view class="text-#6">下单时间</view>
                <view class="text-right text-#3">{{
                  useDayjsFormat(detail.createtime * 1000)
                }}</view>
                <!-- <view class="text-#6">收货方式</view>
                <view class="text-right text-#3">{{ ['', '自提', '邮寄'][detail.shippingMode] }}</view> -->
              </view>
            </view>
            <view
              v-if="logistics.show"
              class="b-t-1px b-t-#e0 b-t-solid px-15px pb-30px"
            >
              <view class="h-70px flex items-center">
                <view class="mr-a text-28px text-#3">物流信息</view>
                <view class="flex text-center text-24px -mx-20px">
                  <view
                    class="mx-10px b-2px b-#e0 rd-full b-solid px-15px text-#6 lh-40px"
                  >联系客服</view>
                  <view
                    class="text-theme-primary bg-theme-primary/10 b-theme-primary mx-10px b-2px rd-full b-solid px-15px lh-40px"
                  >拨打电话</view>
                </view>
              </view>
              <template v-for="(item, i) in logistics.data" :key="i">
                <view class="grid grid-cols-[auto_1fr] gap-y-20px text-24px">
                  <view class="text-#6">{{ item.status }}</view>
                  <view class="text-right text-#3">{{ item.context }}</view>
                </view>
              </template>
            </view>
            <view class="b-t-1px b-t-#e0 b-t-solid px-15px pb-30px">
              <view class="h-70px flex items-center">
                <view class="text-28px text-#3">首期实际支付</view>
              </view>
              <view class="grid grid-cols-[auto_1fr] gap-y-20px text-24px">
                <view class="text-#6">首期支付租金</view>
                <view class="flex">
                  <view class="ml-a w-70% flex">
                    <template v-if="detail.paymentParams?.total_freeze_amount">
                      <view class="text-#3 line-through">¥ {{ detail.paymentParams.total_freeze_amount }}</view>
                    </template>
                    <view class="ml-a text-#3">¥ {{ (detail.params.deposit / 100).toFixed(2) }}</view>
                  </view>
                </view>
              </view>
            </view>
          </template>
          <view
            class="text-theme-primary flex items-center justify-center py-30px text-24px"
            @click="expand = !expand"
          >
            <view class="">{{ expand ? "收起" : "展开" }}</view>
            <view
              class="i-icon-park-outline:down ml-5px"
              :class="{ 'rotate-180deg': expand }"
            ></view>
          </view>
        </view>

        <!--  -->
        <view v-if="flagRent" class="mt-10px rd-16px bg-white px-20px">
          <view class="h-70px flex items-center px-10px text-28px text-#3">租金计划</view>
          <view class="">
            <view
              class="bg-theme-primary/10 grid grid-cols-[auto_1fr] gap-y-20px rd-16px p-30px text-24px"
            >
              <view class="text-#3">总租金</view>
              <view class="text-right text-#3">¥&thinsp;{{
                (detail.params.model.price / 100).toFixed(2)
              }}</view>
              <view class="text-theme-primary">买断尾款</view>
              <view class="text-theme-primary text-right">¥&thinsp;{{ (detail.params.worryMoney / 100).toFixed(2) }}
              </view>
            </view>
          </view>
          <view class="empty-pb-20px">
            <template v-for="(item, i) in scheduleList" :key="item.date">
              <view
                class="flex items-center b-t-1px b-t-#e0 b-t-solid px-15px py-30px"
                :class="{ '!b-none': i === 0 }"
              >
                <view class="flex flex-col text-24px">
                  <view class="flex">
                    <view class="text-#3">第{{ i + 1 }}期</view>
                    <view class="ml-5px text-#6">{{ ["待", "已", "正在"][item._status] }}交租</view>
                  </view>
                  <view class="mt-10px text-#3">{{ item.date }}</view>
                </view>
                <view class="ml-a text-36px text-#3">¥&thinsp;{{ item.price }}</view>
              </view>
            </template>
          </view>
        </view>
      </view>
    </view>

    <view class="safe-pb-15px">
      <view class="h-95px"></view>
    </view>

    <view
      class="fixed bottom-0 w-full overflow-y-hidden bg-white pt-15px safe-pb-15px"
    >
      <scroll-view class="whitespace-nowrap pb-200px -mb-200px" scroll-x>
        <view class="btn-group mx-30px inline-block shrink-0">
          <view class="min-w-690px flex flex-row-reverse gap-x-8px">
            <template v-if="useOrderStatusCheck.quZhiFu(detail)">
              <cm-pay-btn :id="oid" pay-status="2">
                <template #name>
                  <view
                    class="btn btn-primary-black text-36px font-black italic"
                  >去支付</view>
                </template>
              </cm-pay-btn>
            </template>
            <!-- <template v-if="useOrderStatusCheck.xuZu(detail)">
              <view class="btn btn-secondary-theme" @click="handleXuZu({ oid })">续租</view>
            </template> -->
            <template v-if="useOrderStatusCheck.maiDuan(detail)">
              <cm-pay-btn :id="detail.id" pay-status="5">
                <template #name>
                  <view class="btn btn-secondary-theme">买断</view>
                </template>
              </cm-pay-btn>
            </template>
            <template
              v-if="useOrderStatusCheck.qianShuHeTong_JunZiQian(detail)"
            >
              <view
                class="btn btn-primary-black"
                @click="handleQianShuHeTong_JunZiQian({ oid })"
              >
                {{ "签署合同" }}
              </view>
            </template>
            <template v-if="useOrderStatusCheck.qianShouDan(detail)">
              <view
                class="btn btn-primary-black"
                @click="handleQianShouDan({ oid }, `order/detail?oid=${oid}`)"
              >签收单</view>
            </template>
            <template v-if="useOrderStatusCheck.qianChengNuoShu(detail)">
              <view
                class="btn btn-primary-black"
                @click="
                  handleQianChengNuoShu({ oid }, `order/detail?oid=${oid}`)
                "
              >签承诺书</view>
            </template>
            <template v-if="useOrderStatusCheck.chaKanZhangDan(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleChaKanZhangDan({ oid })"
              >查看账单</view>
            </template>
            <!-- <template v-if="useOrderStatusCheck.shouHouXiangQing(detail)">
              <view class="btn btn-secondary-theme" @click="handleShouHouXiangQing({ oid })">售后详情</view>
            </template> -->
            <template v-if="useOrderStatusCheck.queRenShouHuo(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleQueRenShouHuo({ oid })"
              >确认收货</view>
            </template>

            <template v-if="useOrderStatusCheck.qianShuDaiKou(detail)">
              <view
                class="btn btn-primary-black"
                @click="handleQianShuDaiKou({ oid: detail.id })"
              >签署代扣</view>
            </template>
            <!-- <template v-if="useOrderStatusCheck.ziTi(detail)">
              <view class="btn btn-secondary-theme" @click="handleZiTi({ shopInfo: detail.shopsVo })">自提</view>
            </template> -->
            <!-- <template v-if="useOrderStatusCheck.queRenZiTi(detail)">
              <view class="btn btn-secondary-theme" @click="handleQueRenZiTi({ oid })">确认自提</view>
            </template> -->
            <template>
              <view
                class="btn btn-primary-theme !w-180px !text-24px"
                @click="handleFengKongBuLu({ oid, mode: detail.mode })"
              >录入审批材料</view>
            </template>
            <template v-if="useOrderStatusCheck.daiShouHuoLuRu(detail)">
              <view
                class="btn btn-primary-theme !w-180px !text-24px"
                @click="
                  handleShouHuoBuLu({
                    oid,
                    mode: detail.mode,
                    type: detail.extraInfo.type,
                  })
                "
              >提交录单材料</view>
            </template>
            <template v-if="useOrderStatusCheck.dingSunJieGuo(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleDingSunJieGuo({ oid })"
              >定损结果</view>
            </template>
            <template v-if="useOrderStatusCheck.shenQingGuiHuan(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleShenQingGuiHuan({ oid })"
              >申请归还</view>
            </template>
            <template v-if="useOrderStatusCheck.weiYueJin(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleWeiYueJin({ oid })"
              >违约金</view>
            </template>

            <template v-if="useOrderStatusCheck.quXiaoDingDan(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleQuXiaoDingDan({ oid })"
              >取消订单</view>
            </template>
            <template v-if="useOrderStatusCheck.shenQingTuiKuan(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleShenQingTuiKuan({ oid })"
              >申请退款</view>
            </template>
            <template v-if="useOrderStatusCheck.fuWuBaoZhang(detail)">
              <view
                class="btn btn-secondary-theme"
                @click="handleFuWuBaoZhang({ oid })"
              >服务保障</view>
            </template>
            <view
              class="btn btn-secondary-theme"
              @click="handleLianXiShangJia()"
            >联系商家</view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
  <view v-else class="h-100vh flex flex-col items-stretch px-30px py-20px">
    <view class="h-100px rd-16px bg-white"></view>
    <view class="mt-10px h-400px rd-16px bg-white"></view>
    <view
      class="mt-10px flex-1 rd-16px from-white to-transparent bg-gradient-to-b"
    ></view>
  </view>
</template>

<style lang="less" scoped>
.btn-group {
  .btn {
    --uno: 'shrink-0';
    width: 166.5rpx;
    line-height: 80rpx;
    height: 80rpx;

    &.btn-secondary-theme {
      line-height: 76rpx;
    }
  }
}
</style>
